package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.api.NutritionService
import com.example.nutritionmanager.bodys.responseBodys.NutritionAmount
import com.example.nutritionmanager.bodys.responseBodys.UserProfileResponse
import com.example.nutritionmanager.data.UserProfileDataStore
import com.example.nutritionmanager.home.getCurrentDate
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed class AIPromptState {
    object Idle : AIPromptState()
    object Loading : AIPromptState()
    data class Success(val prompt: String) : AIPromptState()
    data class Error(val error: String) : AIPromptState()
}

@HiltViewModel
class AIPromptViewModel @Inject constructor(
    private val nutritionService: NutritionService,
    private val userProfileDataStore: UserProfileDataStore
) : ViewModel() {

    private val _aiPromptState = MutableStateFlow<AIPromptState>(AIPromptState.Idle)
    val aiPromptState: StateFlow<AIPromptState> = _aiPromptState.asStateFlow()

    // 当日摄入数据
    private val _nutritionAmount = MutableStateFlow<List<NutritionAmount>>(emptyList())
    val nutritionAmount: StateFlow<List<NutritionAmount>> = _nutritionAmount.asStateFlow()

    // 用户资料状态
    private val _userProfile = MutableStateFlow<UserProfileResponse?>(null)
    val userProfile: StateFlow<UserProfileResponse?> = _userProfile.asStateFlow()

    init {
        loadAllData()
    }

    // 加载所有数据
    fun loadAllData() {
        viewModelScope.launch {
            _aiPromptState.value = AIPromptState.Loading
            try {
                // 并行获取数据
                val (profile, amounts) = awaitAll(
                    async { fetchUserProfile() },
                    async { fetchDailyNutritionAmount() }
                )

                _userProfile.value = profile as UserProfileResponse?
                _nutritionAmount.value = amounts as List<NutritionAmount>
                _aiPromptState.value = AIPromptState.Success(generateAIPrompt())
            } catch (e: Exception) {
                _aiPromptState.value = AIPromptState.Error(e.localizedMessage ?: "数据加载失败")
            }
        }
    }

    // 获取用户资料
    private suspend fun fetchUserProfile(): UserProfileResponse? {
        return userProfileDataStore.getCurrentUserProfile()
    }
    private suspend fun fetchDailyNutritionAmount(): List<NutritionAmount> {
        return nutritionService.getNutritionAmountByDate(getCurrentDate()).body()?: emptyList()
    }
    fun Int.toChineseGender() = when(this) {
        1 -> "男"
        2 -> "女"
        else -> "未知"
    }

    fun Int.toChinesePeriod() = when(this) {
        1 -> "减脂期"
        2 -> "增肌期"
        else -> "保持期"
    }
    // 生成AI提示消息
    fun generateAIPrompt(): String {
        return buildString {
            userProfile.value?.let { profile ->
                append("用户性别 ${profile.gender.toChineseGender()}，")
                append("年龄${profile.age}岁，")
                append("身高${profile.height}cm，")
                append("体重${profile.weight}kg，")
                append("当前阶段：${profile.period.toChinesePeriod()}。")
            }
            append("今日已摄入：")
            nutritionAmount.value.forEach { amount ->
                append("${amount.nutritionName} ${amount.amount} ${amount.unit}，")
            }
        }
    }
}